package test.marui.com.mytest.view.verifyEditView.view;

import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

/**
 * Created by MR on 2019/1/7.
 */
public class HelpEditText extends AppCompatEditText {

    private OnKeyListener mOnKeyListener;

    public HelpEditText(Context context) {
        super(context);
    }

    public HelpEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HelpEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new MyInputConnection(super.onCreateInputConnection(outAttrs), true);
    }

    public void setDeleteEventListener(OnKeyListener mOnKeyListener) {
        this.mOnKeyListener = mOnKeyListener;
    }

    class MyInputConnection extends InputConnectionWrapper{

        /**
         * Initializes a wrapper.
         * <p>
         * <p><b>Caveat:</b> Although the system can accept {@code (InputConnection) null} in some
         * places, you cannot emulate such a behavior by non-null {@link InputConnectionWrapper} that
         * has {@code null} in {@code target}.</p>
         *
         * @param target  the {@link InputConnection} to be proxied.
         * @param mutable set {@code true} to protect this object from being reconfigured to target
         *                another {@link InputConnection}.  Note that this is ignored while the target is {@code null}.
         */
        MyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        public boolean sendKeyEvent(KeyEvent event) {

            if (HelpEditText.this.mOnKeyListener != null) {
                HelpEditText.this.mOnKeyListener.onKey(HelpEditText.this, event.getKeyCode(), event);
            }

            return super.sendKeyEvent(event);
        }

        public boolean deleteSurroundingText(int beforeLength, int afterLength) {
            if (beforeLength != 0 && beforeLength != 1 && afterLength != 0) {
                return super.deleteSurroundingText(beforeLength, afterLength);
            }else {
                return this.sendKeyEvent(new KeyEvent(0,67)) && this.sendKeyEvent(new KeyEvent(1,67));
            }
        }
    }
}
